package com.monlyu.bo;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.google.common.collect.Lists;
import com.monlyu.exception.MsgException;
import com.monlyu.util.DateUtil;
import com.monlyu.util.StringUtil;
import com.monlyu.vo.Programming;
import com.monlyu.vo.StaffScore;
import com.monlyu.vo.User;

/*******************************************************************************
 * 
 * <b>功能描述☞</b>串联单的后期人员打分<br>
 * 
 * <b>开发公司☞</b>重庆唯尼科技有限公司<br>
 * <b>版权☞</b>本文件归重庆唯尼科技有限公司所有<br>
 * <b>项目名☞</b>news<br>
 * <b>文件路径☞</b>com.monlyu.bo.StaffScoreBo.java<br>
 * <b>开发日期☞</b>2010-3-25 <br>
 * 
 * @author chendan
 * @since JDK 5
 * @version 1.0.8
 * 
 ******************************************************************************/
@Repository(value = "staffScoreBo")
public class StaffScoreBo extends BaseBo {
	private RoleBo roleBo;
	private EnumsBo enumsBo;
	private ProgrammingBo programmingBo;

	public void setProgrammingBo(ProgrammingBo programmingBo) {
		this.programmingBo = programmingBo;
	}

	public void setRoleBo(RoleBo roleBo) {
		this.roleBo = roleBo;
	}

	public void setEnumsBo(EnumsBo enumsBo) {
		this.enumsBo = enumsBo;
	}

	/**
	 * 生成或修改人员的打分表，根据ProStaffInfo中的人员来设置
	 * 
	 * @param proStaffInfo
	 * @param type
	 *            photo-出像人员 maker-制作人员 light-灯光 zimu-字幕
	 * @since chendan 2010-3-26
	 */
	public void createStaffScore(List<User> users, Programming programming,
			String type) {
		String hql = "from com.monlyu.vo.StaffScore s where s.programming.id=? and s.type=?";
		List list = dao.find(hql, new Object[] { programming.getId(), type });
		for (Iterator<User> iterator = users.iterator(); iterator.hasNext();) {
			User user = iterator.next();
			boolean flag = false;// 作标志用，看此user是否已创建了StaffScore对象
			for (Iterator<StaffScore> it = list.iterator(); it.hasNext();) {
				StaffScore staffScore = it.next();
				if (user.getId().equals(staffScore.getUser().getId())) {
					// 如果已创建，则将staffScore从list中删除掉
					list.remove(staffScore);
					flag = true;
					break;
				}
			}
			if (!flag) {
				// 如果没有创建，则要new一个staffScore对象
				StaffScore staffScore = new StaffScore();
				staffScore.setUser(user);
				staffScore.setProgramming(programming);
				staffScore.setType(type);
				dao.insertOrUpdate(staffScore);
			}
		}
		// users循环结束，将没有再选择的人员的StaffScore对象删除掉
		for (Iterator<StaffScore> it = list.iterator(); it.hasNext();) {
			dao.delete(it.next());
		}
	}

	/**
	 * 获取需要打分的人员
	 * 
	 * @param programming
	 *            串联单id
	 * @param type
	 *            打分的人员角色
	 * @return
	 * @since chendan 2010-3-25
	 */
	public List<StaffScore> getGradeUser(Programming programming, String type, Date beginDate,
			Date endDate) {
		// 检查权限
		if ("photo".equals(type)) {
			if (!roleBo.checkPermission("PHOTO_GRADE")) {
				throw new MsgException("对不起，您没有出像打分的权限。");
			}
		} else if ("maker".equals(type)) {
			if (!roleBo.checkPermission("MAKER_GRADE")) {
				throw new MsgException("对不起，您没有制作打分的权限。");
			}
		} else if ("light".equals(type)) {
			if (!roleBo.checkPermission("LIGHT_GRADE")) {
				throw new MsgException("对不起，您没有灯光打分的权限。");
			}
		} else if ("zimu".equals(type)) {
			if (!roleBo.checkPermission("ZIMU_GRADE")) {
				throw new MsgException("对不起，您没有字幕打分的权限。");
			}
		}
		//String string = "from com.monlyu.vo.StaffScore s where s.programming.id=? and s.type=?";
		StringBuilder hql=new StringBuilder();
		List<Object> args = new ArrayList<Object>();
		hql.append("from com.monlyu.vo.StaffScore s where s.type=? and s.programming.id in (");
		args.add(type);
		hql.append("select p.id from com.monlyu.vo.Programming p where p.audit=true ");
		if (programming != null) {
			if (programming.getColumn() != null) {
				hql.append(" and p.column=?");
				args.add(programming.getColumn());
			}
		}
		if (beginDate != null) {
			hql.append(" and p.date>=?");
			args.add(beginDate);
		}
		if (endDate != null) {
			hql.append(" and p.date<?");
			args.add(DateUtil.addDay(endDate, 1));
		}
		hql.append(") order by s.programming.id ");
		return dao.find(hql.toString(),args.toArray());
	}

	/**
	 * 打分
	 * 
	 * @param content
	 * @since chendan 2010-3-26
	 */
	public void grade(String content) {
		String[] contents = content.split(";");
		// 依次保存打的分数
		for (int i = 0; i < contents.length; i++) {
			String[] infos = contents[i].split(",");
			StaffScore staffScore = (StaffScore) dao.get(StaffScore.class, Long
					.valueOf(infos[0]));
			staffScore.setScore(Long.valueOf(infos[1]));
			staffScore.setDate(DateUtil.now());
			staffScore.setGradeUser(curUser());
			dao.insertOrUpdate(staffScore);
		}
	}

	/**
	 * 统计人员的分数
	 * 
	 * @param userIds
	 * @param beginDate
	 * @param endDate
	 * @param programming
	 * @return
	 * @since chendan 2010-3-26
	 */
	/**
	 * @param userIds
	 * @param beginDate
	 * @param endDate
	 * @param programming
	 * @param type
	 * @return
	 * @since chendan 2010-3-26
	 */
	public Object[] countScore(String userIds, Date beginDate, Date endDate,
			Programming programming, String type) {
		// 检查权限
		if (!roleBo.checkPermission("COUNT_ALL")) {
			if ("photo".equals(type)) {
				if (!roleBo.checkPermission("PHOTO_GRADECOUNT")) {
					throw new MsgException("对不起，您没有出像分数统计的权限。");
				}
			} else if ("maker".equals(type)) {
				if (!roleBo.checkPermission("MAKER_COUNT")) {
					throw new MsgException("对不起，您没有制作分数统计的权限。");
				}
			} else if ("light".equals(type)) {
				if (!roleBo.checkPermission("LIGHT_COUNT")) {
					throw new MsgException("对不起，您没有灯光分数统计的权限。");
				}
			} else if ("zimu".equals(type)) {
				if (!roleBo.checkPermission("ZIMU_COUNT")) {
					throw new MsgException("对不起，您没有字幕分数统计的权限。");
				}
			}
		}
		StringBuilder hql = new StringBuilder();
		List<Object> args = Lists.newArrayList();
		hql.append("from com.monlyu.vo.StaffScore s where 1=1 ");
		if (!StringUtil.isEmpty(type)) {
			hql.append(" and s.type=?");
			args.add(type);
		}
		if (StringUtil.isEmpty(userIds) || !roleBo.checkPermission("COUNT_ALL")) {
			hql.append(" and s.user.id=?");
			args.add(curUser().getId());
		} else if (roleBo.checkPermission("COUNT_ALL")) {
			hql.append(" and s.user.id in (?");
			String[] ids = userIds.split(",");
			args.add(Long.parseLong(ids[0]));
			for (int i = 1; i < ids.length; i++) {
				hql.append(" ,?");
				args.add(Long.parseLong(ids[i]));
			}
			hql.append(")");
		}
		hql
				.append(" and s.programming.id in (select p.id from com.monlyu.vo.Programming p where 1=1 ");
		if (programming != null) {
			if (programming.getColumn() != null) {
				hql.append(" and p.column=?");
				args.add(programming.getColumn());
			}
		}
		if (beginDate != null) {
			hql.append(" and p.date>=?");
			args.add(beginDate);
		}
		if (endDate != null) {
			hql.append(" and p.date<?");
			args.add(DateUtil.addDay(endDate, 1));
		}
		hql.append(")");
		List staffScores = dao.find(hql.toString(), args.toArray());
		float sum = 0f;
		for (Iterator<StaffScore> it = staffScores.iterator(); it.hasNext();) {
			Object enumValue;
			StaffScore staffScore = it.next();
			if (staffScore.getScore() != null) {
				enumValue = enumsBo.getEnumValue(staffScore.getScore());
				sum += enumValue == null ? 0 : Long
						.parseLong((String) enumValue);
			}
		}
		return new Object[] { staffScores, Float.valueOf(sum) };
	}
}
